﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using Newtonsoft.Json;

namespace WebApp.Services
{
    public class MongoDbCacheService : ICacheService
    {
        private readonly MongoClient client;

        public MongoDbCacheService(DbConnectionConfigurationServicecs dbConfig)
        {
            //_connectionMultiplexer = ConnectionMultiplexer.Connect(dbConfig.DbConnection.Redis);
            var mongoUrl = new MongoUrl(dbConfig.DbConnection.MongoDb);
            var setting = MongoClientSettings.FromUrl(mongoUrl);


            client = new MongoClient(setting);


        }

        public bool Add(string key, object value)
        {
            var db = client.GetDatabase("CommonDB");
            var collection = db.GetCollection<BsonDocument>("test");

            var document = new BsonDocument
            {
                { "key", key },
                { "value", value.ToString() },
                { "info", new BsonDocument
                {
                    { "x", 111 },
                    { "y", 222 }
                }}
            };

            collection.InsertOne(document);

            return true;
        }

        public object Get(string key)
        {
            var db = client.GetDatabase("CommonDB");
            var collection = db.GetCollection<BsonDocument>("test");

            var m = collection.Find(new BsonDocument
            {
                {
                    "key", key
                }
            }).FirstOrDefault();

            return m.AsBsonValue.ToJson();

           // return m.ToList().FirstOrDefault(c=>c.Name=="value").Value.ToString();

        }





    }
}
